var Single_SMS = {

    init: function () {
        var self = this;

        self.configSendSMS();

        // Character Counter
        jQuery("#sms_txt").charCount({
            count_type: 'up',
            counterText: 'Total Character: '
        });
       /* jQuery("#schedule_date").datepicker({
            inline: true,
            changeMonth: true,
            changeYear: true,
            showOn: "button",
            constrainInput: true,
            buttonText: "Click Here For Date"
        });
        $("#schedule_date").datepicker( "option", "dateFormat", 'yy-mm-dd' );

        jQuery('#schedule_time').timepicker({
            minuteStep: 1,
            showMeridian:false
        });*/
    },

    configSendSMS: function () {
        var self = this;

        $("#send_sms_btn").click(function () {
            if (self.validateSMS()) {
                self.send_SMS('Now');
            }
        });

        $("#send_sms_later_btn").click(function () {
            if (self.validateSMS()) {
                self.send_SMS('Later');
            }
        });

        $("#sms_schedule_modal_btn").click(function () {
            var credit_bal = parseFloat(credit_balance);
            var total_contacts = self.countContacts();
            var schedule_date = $('#schedule_year').val()+'-'+$('#schedule_month').val()+'-'+$('#schedule_day').val();
            var schedule_time = $('#schedule_time').val();
            schedule_date = schedule_date.trim();
            schedule_time = schedule_time.trim();
            if(schedule_date.length == 0 || schedule_time.length == 0 ){
                jLib.serverError("Schedule Date and Schedule Time are required!",false);
            }
            else{
                var schedule_date_time = schedule_date+' '+schedule_time;
                self.do_send_SMS('Later',credit_bal,total_contacts,schedule_date_time);
            }
        });
    },


    getSMSCost: function () {
        var self = this;
        var unit_cost = parseFloat(sms_per_unit_cost);
        var per_count = parseInt(sms_per_unit_count);
        var total_contacts = self.countContacts();

        var sms_txt = $("#sms_txt").val();
        var txt_count = sms_txt.length;

        var messages_count = 0;
        var calc = true;
        while (calc) {
            if (txt_count > per_count) {
                txt_count = txt_count - per_count;
                messages_count++;
                calc = true;
            }
            else {
                txt_count = txt_count - per_count;
                messages_count++;
                calc = false;
            }
        }

        var total_cost_sms = (unit_cost * messages_count) * total_contacts;

        return total_cost_sms.toFixed(2);
    },


    validateSMS: function () {
        var self = this;
        var pass = true;

        var total_contacts = self.countContacts();
        var sms_txt = $("#sms_txt").val();
        var sender_id = $("#sender_id").val();

        var txt_count = sms_txt.length;
        var sender_txt_count = sender_id.length;
        if (txt_count == 0 || sender_txt_count == 0) {
            pass = false;
            var txt = "Text Message and Sender ID are required!"
            //Animate sms box
            $("#widget_sms .widgetcontent p.error").html(txt).show();
            $("#widget_sms").addClass('box-danger').addClass('animate0').addClass('bounceIn');
            setTimeout(function () {
                $("#widget_sms").removeClass('box-danger').removeClass('animate0').removeClass('bounceIn');
            }, 1000);
        }
        else {
            $("#widget_sms .widgetcontent p.error").html('').hide();
            $("#widget_sms").removeClass('box-danger').removeClass('animate0').removeClass('bounceIn');
        }

        if (total_contacts == 0) {
            pass = false;
            var txt = "Please enter contact numbers!"
            //Animate sms box
            $("#widget_contacts_sms .widgetcontent p.error").html(txt).show();
            $("#widget_contacts_sms").addClass('box-danger').addClass('animate1').addClass('bounceIn');
            setTimeout(function () {
                $("#widget_contacts_sms").removeClass('box-danger').removeClass('animate1').removeClass('bounceIn');
            }, 1000);
        }
        else {
            $("#widget_contacts_sms .widgetcontent p.error").html('').hide();
            $("#widget_contacts_sms").removeClass('box-danger').removeClass('animate1').removeClass('bounceIn');
        }

        return pass
    },


    countContacts:function(){
        var sms_contacts = $("#sms_contacts").val();
        var sms_contacts = sms_contacts.trim();
        var contacts_arr = sms_contacts.split(',');
        if(contacts_arr.length == 1 && contacts_arr[0] == ''){
            return 0;
        }
        else{
            return contacts_arr.length;
        }
    },


    send_SMS: function (schedule) {
        var self = this;

        var credit_bal = parseFloat(credit_balance);

        var total_contacts = self.countContacts();

        if(schedule == 'Later'){
            var current_date = new Date();
            var year = current_date.getFullYear();
            var month = current_date.getMonth();
            var day  = current_date.getDate();
            var hour = current_date.getHours();
            var min = current_date.getMinutes();
            $("#sms_schedule_modal form")[0].reset();

            $("#sms_schedule_modal #schedule_date").val(year+'-'+month+'-'+day);
            $("#sms_schedule_modal #schedule_time").val(hour+':'+min);

            $('#sms_schedule_modal').modal({
                backdrop: 'static',
                show: true,
                keyboard: true
            });
            var d = new Date();
            d.setMinutes(d.getMinutes() + 10);
            var time_10_min = d.getHours()+":"+ d.getMinutes();
            $("#schedule_time").val(time_10_min);
        }
        else{
            self.do_send_SMS(schedule,credit_bal,total_contacts);
        }
    },


    do_send_SMS: function (schedule,credit_bal,total_contacts,schedule_date) {
        var self = this;

        var ms = "You are about to send SMS to "+total_contacts+" contacts. Click OK if you want to proceed or Cancel if you want to quit.";

        jConfirm(ms, 'Confirm', function(confirmation) {
            if(confirmation){
                var save = {
                    sms: $("#sms_txt").val(),
                    sender_id:$("#sender_id").val(),
                    sms_contacts:$("#sms_contacts").val(),
                    total_contacts:total_contacts,
                    'schedule':schedule
                }
                var close_schedule = false;
                if(typeof schedule_date != "undefined" ){
                    save['schedule_date'] = schedule_date;
                    close_schedule = true;
                }

                var url = $('#do-sms-url').val();
                var query = 'data=' + encodeURIComponent(JSON.stringify(save));

                $.ajax({
                    url:url,
                    data:query,
                    dataType:'json',
                    type:'POST',
                    success:function (response) {
                        var txt = '';
                        if (typeof response.msg == 'object') {
                            for (megTxt in response.msg) {
                                txt += response.msg[megTxt] + '<br />';
                            }
                        }
                        else {
                            txt = response.msg
                        }
                        //* When everything went on smoothly on the server redirect the user to the appropriate page.*//*
                        if (response.code === 0) {
                            jLib.serverSuccess(txt);
                            //Update Credit Balance
                            jLib.updateCreditBal(response.new_credit_bal);
                            self.clearSMSForm(close_schedule);
                        }
                        //* When there are Errors *//*
                        else if (response.code === 1) {
                            jLib.serverError(txt,false);
                        }
                    },
                    error:function (xhr) {
                        jLib.serverError();
                    }
                });
            }
        });
    },


    clearSMSForm:function(close_schedule){
        var self = this;

        $("#sms_txt").val('').keyup();
        $("#sender_id").val('');
        $("#sms_contacts").val('');
        if(close_schedule){
            $("#close-sms_schedule_modal").click();
        }
    }
};

/* when the page is loaded */
$(document).ready(function () {
    Single_SMS.init();
});

